﻿using Devonline.Entity;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.OData.Query;
using Microsoft.EntityFrameworkCore;

namespace Devonline.AspNetCore.OData;

/// <summary>
/// 基于 OData 和 DataService 的数据增删改查的基础控制器
/// </summary>
/// <typeparam name="TDbContext">数据库上下文</typeparam>
/// <typeparam name="TEntitySet">业务数据类型</typeparam>
/// <typeparam name="TViewModel">业务数据类型的视图模型类型</typeparam>
/// <typeparam name="TKey">主键类型</typeparam>
[Authorize]
[ApiController]
public abstract class ODataModelServiceController<TDbContext, TEntitySet, TViewModel, TKey> :
    DataModelServiceController<TDbContext, TEntitySet, TViewModel, TKey>
    where TDbContext : DbContext
    where TEntitySet : class, IEntitySet<TKey>
    where TViewModel : class, IViewModel<TKey>
    where TKey : IConvertible
{
    public ODataModelServiceController(IDataService<TDbContext, TEntitySet, TKey> dataService) : base(dataService) { }

    /// <summary>
    /// 使用 odata 协议进行查询的 get 请求
    /// </summary>
    /// <returns></returns>
    [HttpGet, EnableQuery]
    public IActionResult Get() => Ok(_dataService.GetQueryable());
}

/// <summary>
/// 基于字符串作为主键的 OData 和 DataService 的数据增删改查的基础控制器
/// </summary>
/// <typeparam name="TDbContext">数据库上下文</typeparam>
/// <typeparam name="TEntitySet">业务数据类型</typeparam>
/// <typeparam name="TViewModel">业务数据类型的视图模型类型</typeparam>
[Authorize]
[ApiController]
public abstract class ODataModelServiceController<TDbContext, TEntitySet, TViewModel> :
    DataModelServiceController<TDbContext, TEntitySet, TViewModel>
    where TDbContext : DbContext
    where TEntitySet : class, IEntitySet<string>
    where TViewModel : class, IViewModel<string>
{
    public ODataModelServiceController(IDataService<TDbContext, TEntitySet> dataService) : base(dataService) { }

    /// <summary>
    /// 使用 odata 协议进行查询的 get 请求
    /// </summary>
    /// <returns></returns>
    [HttpGet, EnableQuery]
    public IActionResult Get() => Ok(_dataService.GetQueryable());
}